package wang.jinggo.web;

import com.ecwid.consul.v1.ConsulClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import wang.jinggo.errcode.CommonResultCode;
import wang.jinggo.errcode.Result;
import wang.jinggo.service.ConsulService;
import wang.jinggo.util.ResultUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Consul注册服务Controller类
 *
 * @author liuc
 * @create 2018-07-11
 */
@RestController
@RequestMapping("/consul")
public class ConsulController {

    private final static Logger LOG = LoggerFactory.getLogger(ConsulController.class);

    @Autowired
    private ConsulService consulService;

    //注销所有未通过的服务实例
    @RequestMapping(value = "clearAllFailingService",method = RequestMethod.GET)
    public Result<Object> clearAllFailingService(HttpServletRequest request) {
        try {
            List<String> data = consulService.clearAllFailingService();
            return new ResultUtil<Object>().setData(data);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return new ResultUtil<Object>().setErrorMsg("添加失败");
        }
    }

    //注销serviceName未通过的服务实例
    @RequestMapping(value = "clearFailingServiceByName",method = RequestMethod.GET)
    public ResponseEntity<Map<String, Object>> clearFailingServiceByName(HttpServletRequest request, @RequestParam String serviceName) {
        try {
            List<String> data = consulService.clearFailingServiceByName(serviceName);
            return new ResponseEntity<Map<String, Object>>(CommonResultCode.e0.toMap(data), HttpStatus.OK);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return new ResponseEntity<Map<String, Object>>(CommonResultCode.e700101.toMap("系统错误"), HttpStatus.OK);
        }
    }
}
